﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsJobCategoryTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
    /// <summary>
    /// Job Category Business Object
    /// </summary>

    public class JobCategory : BOBase
    {


        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected JobCategory() { }

        #endregion

        #region Public Properties

        #region Instance Properties

        /// <summary>
        /// PKID of the JobCategory.
        /// </summary>
        public int JobCategoryID
        {
            get { return _jobcategoryID; }
            set
            {
                if (_jobcategoryID != value)
                {
                    if (OnPropertyChanging("JobCategoryID", _jobcategoryID, value))
                    {
                        int oldValue = _jobcategoryID;
                        _jobcategoryID = value;

                        OnPropertyChanged("JobCategoryID", oldValue, value);
                    }
                }
            }
        }  private int _jobcategoryID = -1;

        /// <summary>
        /// Job Category Value.
        /// </summary>
        public string JobCategoryName
        {
            get { return _jobcategoryname; }
            set
            {
                if (_jobcategoryname != value)
                {
                    if (OnPropertyChanging("JobCategoryName", _jobcategoryname, value))
                    {
                        string oldValue = _jobcategoryname;
                        _jobcategoryname = value;
                        OnPropertyChanged("JobCategoryName", oldValue, value);
                    }
                }
            }
        }  private string _jobcategoryname = null;


        /// <summary>
        /// Job Category Description.
        /// </summary>
        public string JobCategoryDescription
        {
            get { return _jobcategorydescription; }
            set
            {
                if (_jobcategorydescription != value)
                {
                    if (OnPropertyChanging("JobCategoryDescription", _jobcategorydescription, value))
                    {
                        string oldValue = _jobcategorydescription;
                        _jobcategorydescription = value;
                        OnPropertyChanged("JobCategoryDescription", oldValue, value);
                    }
                }
            }
        }  private string _jobcategorydescription = null;


        /// <summary>
        /// Date/time at which the JobCategory was created.
        /// </summary>
        public DateTime? AddedDate
        {
            get { return _addedDate; }
            set
            {
                if (_addedDate != value)
                {
                    if (OnPropertyChanging("AddedDate", _addedDate, value))
                    {
                        DateTime? oldValue = _addedDate;
                        _addedDate = value;
                        OnPropertyChanged("AddedDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _addedDate = null;

        /// <summary>
        /// Date/time at which the JobCategory was updated.
        /// </summary>
        public DateTime? UpdateDate
        {
            get { return _updateDate; }
            set
            {
                if (_updateDate != value)
                {
                    if (OnPropertyChanging("UpdateDate", _updateDate, value))
                    {
                        DateTime? oldValue = _updateDate;
                        _updateDate = value;
                        OnPropertyChanged("UpdateDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _updateDate = null;

        
        /// <summary>
        /// True iff the Admin has made this JobCategory Active (i.e. to be used in the application).
        /// </summary>
        public bool IsActive
        {
            get { return _isActive; }
            set
            {
                if (_isActive != value)
                {
                    if (OnPropertyChanging("IsActive", _isActive, value))
                    {
                        bool oldValue = _isActive;
                        _isActive = value;
                        OnPropertyChanged("IsActive", oldValue, value);
                    }
                }
            }
        }  private bool _isActive = false;

        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty JobCategory object.
        /// </summary>
        public static JobCategory CreateNew()
        {
            JobCategory obj = new JobCategory();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;

            obj.AddedDate = DateTime.Now;
            obj.UpdateDate = DateTime.Now;
            obj.IsActive = true;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static JobCategory CreateNew(JobCategoryCollection collection)
        {
            JobCategory obj = CreateNew();

            // Get next/unique ID for the new object.
            int minVal = 0;
            foreach (JobCategory jobcategory in collection)
            {
                if (jobcategory.JobCategoryID < minVal)
                    minVal = jobcategory.JobCategoryID;
            }
            obj.JobCategoryID = --minVal;
            collection.Add(obj);

            return (obj);
        }

        #endregion

        #region GetAllJobCategories

        /// <summary>
        /// Returns a collection of all JobCategory.
        /// </summary>
        public static JobCategoryCollection GetAllJobCategories()
        {
            JobCategoryTableAdapter adapter = new JobCategoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsJobCategory.JobCategoryDataTable tbl = adapter.GetData(null);

            JobCategoryCollection list = new JobCategoryCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsJobCategory.JobCategoryRow row in tbl.Rows)
                {
                    JobCategory jobcategory = new JobCategory();
                    RelationalToObject(jobcategory, row);
                    list.Add(jobcategory);
                }
            }

            return (list);
        }

        #endregion

        #region GetJobCategoryByID

        /// <summary>
        /// Returns an JobCategory object for the specified 'JobCategoryID' or null if no JobCategory with the specified parameter(s) exists.
        /// </summary>
        public static JobCategory GetJobCategoryByID(int jobcategoryid)
        {
            JobCategoryTableAdapter adapter = new JobCategoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsJobCategory.JobCategoryDataTable tbl = adapter.GetData(jobcategoryid);

            if (tbl.Rows.Count == 1)
            {
                JobCategory jc = new JobCategory();
                RelationalToObject(jc, tbl.Rows[0]);
                return (jc);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'JobCategoryID' returned more than one record.");

            return (null);
        }

        #endregion

        #region GetJobCategoryByName

        /// <summary>
        /// Returns an JobCategory object for the specified 'JobCategoryName' or null if no JobCategory with the specified parameter(s) exists.
        /// </summary>
        public static JobCategory GetJobCategoryByName(string jobcategoryname)
        {
            JobCategoryTableAdapter adapter = new JobCategoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsJobCategory.JobCategoryDataTable tbl = adapter.GetDataByJobCategoryName(jobcategoryname);

            if (tbl.Rows.Count == 1)
            {
                JobCategory jc = new JobCategory();
                RelationalToObject(jc, tbl.Rows[0]);
                return (jc);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'jobcategoryname' returned more than one record.");

            return (null);
        }

        #endregion

        #region GetJobCategoryByJobCategoryName

        /// <summary>
        /// Returns an JobCategory object for the specified 'JobCategoryName' or null if no JobCategory with the specified parameter(s) exists.
        /// </summary>
        public static JobCategory GetJobCategoryByJobCategoryName(string jobcategoryname)
        {
            JobCategoryTableAdapter adapter = new JobCategoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsJobCategory.JobCategoryDataTable tbl = adapter.GetDataByJobCategoryName(jobcategoryname);

            if (tbl.Rows.Count == 1)
            {
                JobCategory jobcategoryObj = new JobCategory();
                RelationalToObject(jobcategoryObj, tbl.Rows[0]);
                return (jobcategoryObj);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'JobCategory' returned more than one JobCategory.");

            return (null);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the specified JobCategory.
        /// </summary>
        public static void Update(JobCategory obj)
        {
            bool updateJobCategory = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updateJobCategory = (obj.ObjState != ObjectState.Unchanged);

                if (!updateJobCategory)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;

            dsJobCategory.JobCategoryDataTable tbl = null;
            if (updateJobCategory)
            {
                //obj.SuppressClearRolesOnUserIDChanged = (obj.ObjState == ObjectState.Added);

                JobCategoryTableAdapter adapter = new JobCategoryTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();


                tbl = new dsJobCategory.JobCategoryDataTable();
                dsJobCategory.JobCategoryRow row = tbl.NewJobCategoryRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }


       

        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted) && (JobCategoryID <= 0))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("JobCategoryID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

                // JobCategory is required.
                if ((JobCategoryName == null) || (JobCategoryName.Trim().Length == 0))
                {
                    Errors.Add(new ValidationError("JobCategoryName", "JobCategory is required.", ValidationError.Severity.Error));
                }
                else if (ObjState == ObjectState.Added)
                {
                    
                }

            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("JobCategory: JCID={0}, JobCategoryName={1}, {2}", JobCategoryID, JobCategoryName, JobCategoryDescription));
        }

        #endregion

        #endregion

        #region Privates


        #endregion

    }

    /// <summary>
    /// Collection of 0 or more SubAdmin objects.
    /// </summary>

    public class JobCategoryCollection : List<JobCategory>
    {
        #region Types

        public class UserComparer : IComparer<JobCategory>
        {
            public int Compare(JobCategory user1, JobCategory user2)
            {
                return (String.Compare(user1.JobCategoryName, user2.JobCategoryName));
            }
        }

        #endregion

        #region Public Methods

        #region FindByJobCategoryID

        public JobCategory FindByJobCategoryID(int jobcategoryID)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].JobCategoryID == jobcategoryID)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #region FindByJobCategory

        /// <summary>
        /// Case insensitve compare.
        /// </summary>
        public JobCategory FindByJobCategory(string jobcategoryname)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].JobCategoryName == jobcategoryname)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion

    }
}
